import React, {FC, useEffect, useMemo, useState} from 'react'
import {Modal, Form, Input, Table, Pagination, message} from 'antd'
import type {FormInstance} from 'antd/es/form'
import SearchForm from '@/components/SearchForm'
import {changeHistoryFleet, getFleetList} from '@/service/customer/fleet'
import {FleetColums} from '../constant'

interface ReplaceFleetType {
	replaceFleetVisivle: boolean
	setReplaceFleetVisivle: (visible: boolean) => void
	value: any
	callBack: any
}

function Fleet({value, onChange, callBack}: any) {
	const [visible, setVisible] = useState(false)
	const [fleetHistoryLoading] = useState(false)
	const [fleetLoading, setFleetLoading] = useState(false)
	const [fleetTotal, SetFleetTotal] = useState(0)
	const [fleetPagination, setFleetPagination] = useState({
		current: 1,
		pageSize: 10,
	})
	const [fleetList, setFleetList] = useState<any[]>([])
	const [selectedRow, setSelectedRow] = useState<any>([])

	const FleetFormItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					key: 'fleetName',
					name: 'fleetName',
					label: '车队名称',
				},
				{
					type: 'input',
					key: 'captainName',
					name: 'captainName',
					label: '车队长名称',
				},
				{
					type: 'input',
					key: 'captainPhone',
					name: 'captainPhone',
					label: '车队长电话',
				},
			],
		},
	]

	const onOpenFleet = () => {
		setVisible(true)
	}
	const onSaveFlettHistory = () => {
		if (selectedRow.length) {
			const va = fleetList.find((item: any) => item.id === selectedRow[0])
			callBack(va)
			onChange(va.fleetName)
			setSelectedRow([])
			setVisible(false)
		} else {
			message.error('请选择车队后再确定')
		}
	}
	const getFleetData = async (params: any,page:any) => {
		const obj = {
			...params,
			current: page.current,
			size: page.pageSize,
		}
		setFleetLoading(true)
		const data = await getFleetList(obj).catch(() => {
			setFleetLoading(false)
		})
		if (data.code === 0) {
			setFleetList(data.data.records)
			SetFleetTotal(data.data.total || 0)
		}
		setFleetLoading(false)
	}

	useEffect(() => {
		if (visible) {
			const data = {
				current:1,
				pageSize:10
			}
			getFleetData({},data)
		}
	}, [visible])

	const paginationChange = (current: any, pageSize: number) => {
		setFleetPagination({
			current,
			pageSize,
		})
		const data = {
			current,
			pageSize
		}
		getFleetData({},data)
	}
	return (
		<div>
			<Input
				placeholder="请选择"
				value={value || ' '}
				onClick={onOpenFleet}
			/>
			<Modal
				title="选择车队"
				open={visible}
				onCancel={() => {
					setSelectedRow([])
					setVisible(false)
				}}
				forceRender
				width={1000}
				onOk={onSaveFlettHistory}
				okButtonProps={{loading: fleetHistoryLoading}}>
				<div className="addVehicleInfo">
					<div className="searchBox">
						<SearchForm
							formLayout={{
								labelCol: {flex: '90px'},
								wrapperCol: {flex: '1'},
							}}
							formItems={FleetFormItems}
							onReset={() => {
								getFleetData({},{current: 1,pageSize: 10,})
							}}
							onFinish={(values) => {
								setFleetPagination({current: 1,pageSize: 10,})
								getFleetData(values,{current: 1,pageSize: 10,})
							}}
						/>
					</div>
					<div className="content">
						<Table
							columns={FleetColums}
							rowKey="id"
							dataSource={fleetList}
							loading={fleetLoading}
							rowSelection={{
								type: 'radio',
								selectedRowKeys: selectedRow,
								onChange: (selectedRowKeys: React.Key[]) => {
									setSelectedRow(selectedRowKeys)
								},
							}}
							scroll={{x: 1300, y: 400}}
							pagination={false}
						/>
						<div className="pagination">
							<Pagination
								defaultCurrent={1}
								current={fleetPagination.current}
								total={fleetTotal}
								showTotal={(total, range) =>
									`第  ${range[0]} - ${range[1]} 条 / 总共 ${total} 条`
								}
								showSizeChanger
								showQuickJumper
								onChange={paginationChange}
							/>
						</div>
					</div>
				</div>
			</Modal>
		</div>
	)
}

const replaceFleetModal: FC<ReplaceFleetType> = ({
	replaceFleetVisivle,
	setReplaceFleetVisivle,
	value,
	callBack,
}) => {
	const [saveLoading] = useState(false)
	// const [datas,setDatas] = useState<any>(value||{})

	// useEffect(()=>setDatas(value),[value])
	const datas = useMemo(() => value, [value])

	const formRef = React.useRef<FormInstance>(null)

	const onSave = async () => {
		try {
			await formRef.current?.validateFields()
			if (formRef.current?.getFieldValue('fleet')) {
				const res = await changeHistoryFleet({
					fleetId: formRef.current?.getFieldValue('fleet'),
					id: datas.id,
				})
				if (res.success) {
					message.success(res.msg)
					callBack()
					setReplaceFleetVisivle(false)
				}
			} else {
				message.error('未选择新车队')
			}
		} catch (err: any) {
			message.error(err)
		}
	}

	return (
		<Modal
			title="更换车队"
			open={replaceFleetVisivle}
			onCancel={() => {
				setReplaceFleetVisivle(false)
			}}
			width={500}
			// forceRender
			onOk={onSave}
			okButtonProps={{loading: saveLoading}}>
			<div className="replaceFleet">
				<Form
					key={datas?.id || Math.random()}
					ref={formRef}
					layout="horizontal"
					labelCol={{flex: '140px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					initialValues={{
						fleetName: datas?.fleetName,
						captainName: datas?.captainName,
						captainPhone: datas?.captainPhone,
					}}
					name="PersonalInformationFom">
					<Form.Item label="当前车队名称" name="fleetName">
						<Input disabled />
					</Form.Item>
					<Form.Item label=" 车队长名称" name="captainName">
						<Input disabled />
					</Form.Item>
					<Form.Item label=" 车队长联系方式" name="captainPhone">
						<Input disabled />
					</Form.Item>
					<Form.Item
						label="更换目的车队"
						name="newFleetName"
						rules={[{required: true}]}>
						<Fleet
							callBack={(a: any) => {
								if (a) {
									formRef.current?.setFieldValue(
										'newCaptainName',
										a.captainName,
									)
									formRef.current?.setFieldValue(
										'newCaptainPhone',
										a.captainPhone,
									)
									formRef.current?.setFieldValue(
										'fleet',
										a.id,
									)
								}
							}}
						/>
					</Form.Item>
					<Form.Item
						label=" 更换目的车队长名称"
						name="newCaptainName">
						<Input disabled />
					</Form.Item>
					<Form.Item
						label="更换目的车队长联系方式"
						name="newCaptainPhone">
						<Input disabled />
					</Form.Item>
					<Form.Item
						label="id"
						name="fleet"
						style={{display: 'none'}}>
						<Input disabled />
					</Form.Item>
				</Form>
			</div>
		</Modal>
	)
}

export default replaceFleetModal
